import {
  ExportOutlined,
  EyeOutlined,
  ImportOutlined,
  InboxOutlined,
  PlusOutlined,
  TableOutlined,
} from '@ant-design/icons';
import type {ActionType, ProColumns, ProFormInstance} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import {
  Alert,
  Button,
  Image,
  Form,
  Modal,
  Space,
  UploadFile,
  message,
  Spin, Result, Tooltip, Input
} from 'antd';
import React, {useRef, useState} from 'react';
import {
  addFormData,
  removeFormData,
  page,
  formField,
  updateFormData,
  exportExcel,
  downloadTemplate,
  importExcel,
} from './service';
import {useRequest, useSearchParams} from "@@/exports";
import {BetaSchemaForm} from '@ant-design/pro-components';
import {getFormOne} from '../dynamic-form/design-form/service';
import {getFilterOne} from '../filter/service';
import {history} from '@umijs/max'
import TypeCascader from '@/components/TypeCascader';
import Dragger from 'antd/es/upload/Dragger';
import styles from './style.less'
import CustomImgUpload from '@/components/CustomImgUpload';
import CustomFileUpload from '@/components/CustomFileUpload';
import {queryListForm} from "@/pages/dynamic-form/list-form/service";

const handleImport = async (formId: any, file: UploadFile, type: any) => {
  const hide = message.loading('正在开始导入');

  try {
    const formData = new FormData();
    formData.append("file", file.originFileObj as any)
    formData.append("formId", formId)
    formData.append("type", type)
    const res = await importExcel(formData as any)
    hide();
    if (res?.code === 0) {
      message.success('导入成功');
      return true;
    } else {
      message.error('导入失败请重试！');
      return false;
    }
  } catch (error) {
    hide();
    return false;
  }
};

const handleTemplate = async (formId: any,) => {
  const hide = message.loading('正在下载');

  try {
    const res: any = await downloadTemplate({
      formId: formId,
      fileName: "导入模板"
    })
    // console.log(res);

    hide();
    if (res?.data instanceof Blob) {
      message.success('下载成功');
    } else {
      message.error('下载失败请重试！');
    }
    return true;
  } catch (error) {
    console.log(error);
    hide();
    message.error('下载失败请重试！');
    return false;
  }
};

const handleExport = async (formId: any,) => {
  const hide = message.loading('正在导出');

  try {
    const res: any = await exportExcel({
      formId: formId,
      fileName: formId + '_产品明细_' + new Date().toLocaleDateString()
    })
    hide();
    if (res?.data instanceof Blob) {
      message.success('导出成功');
    } else {
      message.error('导出失败请重试！');
    }
    return true;
  } catch (error) {
    console.log(error);
    hide();
    message.error('导出失败请重试！');
    return false;
  }
};

const handleAdd = async (formId: any, value: string) => {
  const hide = message.loading('正在添加');

  try {
    await addFormData({
      formType: formId,
      value: value
    })
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

const handleUpdate = async (dataId: any, formId: any, value: string) => {
  const hide = message.loading('正在编辑');

  try {
    await updateFormData({
      id: dataId,
      formType: formId,
      value: value
    });
    hide();
    message.success('编辑成功');
    return true;
  } catch (error) {
    hide();
    message.error('编辑失败请重试！');
    return false;
  }
};

const handleRemove = async (selectedRows: any[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeFormData({
      idList: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
  const [searchParams, setSearchParams] = useSearchParams();
  const formId = searchParams.get('formId');
  const type = searchParams.get('type');
  const [searchOps, setSearchOps] = useState([])
  const [isOpen, setOpen] = useState(false)
  const [importing, setImporting] = useState(false)
  const [typeSelected, setTypeSelected] = useState<(string | number)[]>([])
  /**
   * 分类选中值
   */
  const [selectedOptions, setSelectedOptions] = useState<any>([])

  // 导入
  const [fileList, setFileList] = useState<any[]>([])
  const [editForm] = Form.useForm()

  // 筛选条件
  useRequest(async () => {
    const lastId = typeSelected?.[typeSelected?.length - 1]
    if (!lastId) return
    let res = await getFilterOne({
      categoryId: lastId,
    });

    // console.log('res', res);

    if (!res?.data) {
      res = await getFormOne({
        type: typeSelected?.[typeSelected.length - 1]
      });
      // console.log('res2', res);
      if (!res?.data) {
        setSearchOps([])
        return
      }
      const ret = res?.data?.formHeaderList?.map((item: any) => ({
        ...item,
        title: item.property,
        value: item.id,
        label: item.property,
        key: item.id,
        // children: [{ label: 'aaa', value: 0 }]
      }))

      setSearchOps(ret)
    } else {

      if (!res) {
        setSearchOps([])
        return
      }

      const value = res?.data?.value
      let ret = []
      try {
        ret = JSON.parse(value)
        setSearchOps(ret)
      } catch (e) {
      }
    }
    return res;
  }, {
    refreshDeps: [typeSelected, formId],
  });

  const getTableColumns = (data: any[]) => {
    return data?.map((item: any, index: number) => {
      const newItem: any = {
        ...item,
        title: item.property,
        dataIndex: item.name,
        key: item.name,
        valueType: item.inputType,
        hideInSearch: true,
        // render(dom: any, record: any) {
        //   return record[item.name] || '-' + ''
        // }
      }
      if (index === 0) {
        newItem.fixed = 'left'
        newItem.ellipsis = true
        // newItem.width = 190
        newItem.render = (dom: any, record: any) =>{
          return <Tooltip title={record[item.name]}>
            <div style={{width: 190, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>{record[item.name] || '-' + ''}</div>
          </Tooltip>
        }
        //设置组件宽度
        // if(item.inputType === 'input') {
        //   newItem.renderFormItem = () => {
        //     return <Input style={{width: '100%'}}/>
        //   }
        // }
      }
      if (item.inputType === 'imageUpload') {
        // newItem.width = '100%'
        newItem.renderFormItem = () => {
          return <CustomImgUpload/>
        }
        newItem.colProps = {
          span: 24
        }
        newItem.render = (text: any, record: any) => {
          return record?.[item.name]?.url ? <Image width={50} preview={{
            mask: <EyeOutlined/>
          }} src={record?.[item.name]?.url}/> : '-'
        }
      }
      if (item.inputType === 'fileUpload') {
        // newItem.width = '100%'
        newItem.colProps = {
          span: 24
        }
        newItem.renderFormItem = () => {
          return <CustomFileUpload/>
        }
        newItem.render = (text: any, record: any) => {
          return record?.[item.name] ? <Space wrap>
            {record?.[item.name]?.map?.((it: any, index: number) => {
              return <div key={it?.url + index}>
                <a href={it?.url}>{it?.name}</a>
              </div>
            })}
          </Space> : '-'
        }
      }
      if (item.inputType === 'textarea') {
        newItem.colProps = {
          span: 24
        }
      }
      if (['select', 'radio'].includes(item.inputType)) {
        newItem.valueType = 'select'
        newItem.valueEnum = newItem.options?.split(',')?.reduce((ret: any, item: any) => {
          ret[item] = {text: item}
          return ret
        }, {})
      }
      return newItem
    }) || []
  }
  const getFormFieldById = async (formId: any) => {
    const res = await formField({
      formId: formId,
    });
    return {
      data: getTableColumns(res.data || [])
    }
  }

  //随机找一个已经绑定分类的表格
  const {loading: randomLoading} = useRequest(async () => {
    const res = await queryListForm({
      page: 1,
      size: 30
    });

    return {
      data: res?.data?.current_data?.find(item => !!item.type)
    }
  }, {
    ready: !formId,
    onSuccess(data) {
      if (data?.id) {
        setSearchParams({formId: data?.id, type: data?.type})
        actionRef.current?.reload()
      }
    }
  });

  const {data: dynamicCols = [], loading: fieldLoading} = useRequest(async () => {
    return getFormFieldById(formId)
  }, {
    refreshDeps: [formId], ready: !!formId
  });

  /**
   * type换formId
   */
  const {run: findFormIdByType} = useRequest(getFormOne, {
    manual: true,
    onSuccess(data) {
      setSearchParams({
        formId: data?.id || "",
        type: (typeSelected?.[typeSelected?.length - 1] || '') as any
      })
    }
  });

  const columns: ProColumns<any>[] = [
    {
      title: '分类名称',
      dataIndex: 'type',
      hideInForm: true,
      hideInTable: true,
      valueType: 'cascader',
      fieldProps: {},
      renderFormItem: () => {
        return <TypeCascader
          label={''}
          name="type"
          type={type}
          formId={formId}
          // style={{ height: 300 }}
          onChange={async (val: any, selectedOptions: any) => {
            // console.log(val, selectedOptions)
            setSelectedOptions(selectedOptions)
            setTypeSelected(val)
            await findFormIdByType({
              type: val?.[val?.length - 1],
            })
            actionRef.current?.reloadAndRest?.()
          }}
        />
      }
    },
    {
      title: '关键词',
      dataIndex: 'keyword',
      hideInForm: true,
      hideInTable: true,
      hideInSearch: !formId,
      valueType: 'input',
    },
    ...(dynamicCols || []),
    ...searchOps?.filter((item: any) => {
      const children = item?.children
      if (children?.length) {
        return children?.some?.((it: any) => {
          return it.isShow
        })
      } else {
        return false
      }
    })?.map((item: any) => {
      const valueEnum: any = {}
      item?.children?.filter((item: any) => item?.isShow)?.forEach((item: any) => {
        valueEnum[item.filterValue] = {
          text: item.filterValue,
          status: item.filterValue,
        }
      })
      return {
        ...item,
        label: item?.name,
        value: item?.id,
        key: item?.id,
        hideInTable: true,
        valueType: 'select',
        valueEnum,
      }
    })
  ];

  if (dynamicCols?.length) {
    columns.push({
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 80,
      render: (_, record) => {
        return <BetaSchemaForm<any>
          key="edit"
          layoutType={'ModalForm'}
          // initialValues={record}
          form={editForm}
          onFinish={async (values) => {
            const isOk = await handleUpdate(record?.key, formId, JSON.stringify(values))
            if (isOk) {
              actionRef.current?.reload()
            }
            return isOk
          }}
          modalProps={{
            destroyOnClose: true,
            title: "编辑",
            width: "500px",
            onCancel() {
              setFileList([])
            }
          }}
          trigger={<a onClick={() => {
            editForm.setFieldsValue(record)
          }}>编辑</a>}
          columns={dynamicCols}
        />
      },
    })
  }

  const getDataList = async (list: any[]) => {
    let dataList: any[] = []

    list?.forEach((item: any) => {
      try {
        const valObj = JSON.parse(item?.value);
        dataList.push({
          ...valObj,
          key: item?.id,
          formId: item?.formType
        });
      } catch (e) {

      }
    })

    return {
      dataList
    }
  }

  return (
    <PageContainer>
      <Spin spinning={fieldLoading}>
        <ProTable
          headerTitle="产品明细"
          actionRef={actionRef}
          rowKey="key"
          scroll={{x: 'max-content'}}
          className={styles.table}
          search={{
            labelWidth: 120,
          }}
          formRef={formRef}
          onReset={() => {
            setTypeSelected([])
            setSearchParams({
              formId: '',
              type: ''
            })
            formRef.current?.setFieldsValue({
              type: null
            })
          }}
          toolBarRender={() => [
            <BetaSchemaForm<any>
              key="primary"
              layoutType={'ModalForm'}
              // grid={true}
              // rowProps={{
              //   gutter: [16, 16],
              // }}
              // colProps={{
              //   span: 12,
              // }}
              onFinish={async (values) => {
                // console.log(values);
                const isOk = await handleAdd(formId, JSON.stringify(values))
                if (isOk) {
                  actionRef.current?.reload()
                }
                return isOk
              }}
              modalProps={{
                destroyOnClose: true,
                title: "新增数据",
                width: "500px",
              }}
              trigger={<Button type="primary" onClick={() => {
                // setImageUrl('')
                setFileList([])
              }}>
                <PlusOutlined/> 新建
              </Button>}
              columns={dynamicCols || []}
            />,
            <Button icon={<TableOutlined/>} key={'design'} onClick={() => {
              history.push(`/dynamic-form/design-form?formId=${formId}`)
            }}>表格管理</Button>,
            <Button icon={<ImportOutlined/>} key={'import'} onClick={() => {
              setOpen(true)
              setFileList([])
            }}>批量导入</Button>,
            formId && <Button icon={<ExportOutlined/>} key={'export'} onClick={() => {
              handleExport(formId)
            }}>批量导出</Button>,
          ]}
          request={async ({
                            pageSize, current, keyword,
                            // eslint-disable-next-line @typescript-eslint/no-unused-vars
                            type,
                            ...other
                          }: any) => {
            if (!formId) return {data: []}
            const res = await page({
              size: pageSize,
              page: current,
              formId: formId,
              keyword,
              extra: other
            });
            const list = res.data?.current_data;
            const total = res.data?.total_records;
            const {dataList} = await getDataList(list)

            return {
              total,
              data: dataList || [],
            }
          }}
          columns={columns}
          rowSelection={(dynamicCols?.length) ? {
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          } : undefined}
          tableRender={({}, defaultDom) => {
            if (!type) {
              return <Result
                style={{backgroundColor: '#fff'}}
                title="请选择分类"
              />
            }
            if (!formId && !randomLoading) {
              return selectedOptions?.[selectedOptions?.length - 1]?.children?.length ? <Result
                style={{backgroundColor: '#fff'}}
                title="仅支持子分类绑定表格，请选择子分类"
              /> : <Result
                style={{backgroundColor: '#fff'}}
                title="该分类暂无关联的表格数据，您可以选择Excel上传自动生成"
                extra={<Space key={'space'}>
                  <Button type={'primary'} icon={<ImportOutlined/>} key={'import'} onClick={() => {
                    setOpen(true)
                    setFileList([])
                  }}>批量导入</Button>
                </Space>
                }
              />
            }
            return defaultDom
          }}
        />
      </Spin>

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              {/*<span>*/}
              {/*  服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万*/}
              {/*</span>*/}
            </div>
          }
        >
          <Button
            danger
            onClick={async () => {
              Modal.confirm({
                getContainer() {
                  return document.body
                },
                title: `确认删除 ${selectedRowsState.length} 条数据?`,
                content: `请谨慎操作，删除后不可恢复`,
                async onOk() {
                  await handleRemove(selectedRowsState);
                  setSelectedRows([]);
                  actionRef.current?.reloadAndRest?.();
                }
              })
            }}
          >
            批量删除
          </Button>
          {/*<Button type="primary">批量审批</Button>*/}
        </FooterToolbar>
      )}
      <Modal
        title="批量导入"
        open={isOpen}
        onCancel={() => {
          setOpen(false)
          setFileList([])
        }}
        destroyOnClose
        okText="开始导入"
        okButtonProps={{
          loading: importing
        }}
        onOk={async () => {
          if (fileList?.length) {
            setImporting(true)
            const flag = await handleImport(formId, fileList?.[0], type)
            if (flag) {
              setFileList([])
              setOpen(false)
              setTimeout(async () => {
                await findFormIdByType({
                  type
                })
                actionRef.current?.reloadAndRest?.()
              }, 2000)
            }
            setImporting(false)
          } else {
            message.warning('请选择文件!')
          }

        }}
      >
        {formId && <Alert
          message="使用提示"
          description={
            <Space direction='vertical'>
              <span>1.点击此处上传包含所需数据的Excel文件。</span>
              <span>2.请确保您的文件格式正确，并含有相应的列标题（如“电压”，“电流”，“封装”等）。</span>
              <span>3.支持拖拽文件至此区域进行批量导入。</span>
              <span>4.选择文件后，点击“开始导入”按钮启动批量处理。</span>
              <span>5.导入过程中，请勿关闭浏览器窗口或刷新页面。</span>
            </Space>
          }
          type="info"
          action={
            <Space direction="vertical">
              <Button size="small" type="primary" onClick={() => {
                handleTemplate(formId)
              }}>
                下载模板
              </Button>
            </Space>
          }
          style={{marginBottom: 20}}
        />}
        <Dragger multiple={false} maxCount={1} fileList={fileList}
          // customRequest={() => Promise.resolve()}
                 onChange={(vals) => {
                   setFileList(vals?.fileList?.map(item => ({...item, status: 'done'})) || [])
                 }}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined/>
          </p>
          <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
          <p className="ant-upload-hint">支持单次或批量上传。严禁上传公司数据或其他被禁止的文件。</p>
        </Dragger>
      </Modal>
    </PageContainer>
  );
};

export default TableList;
